﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HRProject.Code.DTO;
using HRProject.Code.DAO;
using HRProject.Code.Common;
using System.Text;

namespace HRProject.Worktime
{
    public partial class AjaxWorktime : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sAction = Request.Params["action"];
            string sJobTitleId = Request.Params["jobTitleId"];
            string sYear = Request.Params["year"];
            string sMonth = Request.Params["month"];
            string sPageIndex = Request.Params["pageIndex"];

            string sAgentId = Request.Params["agentId"];
            string sDay = Request.Params["day"];

            StringBuilder result = new StringBuilder();
            int errorCode = 0;
            string error = string.Empty;
            string status = "true";

            try
            {
                int year = int.Parse(sYear);
                int month = int.Parse(sMonth);
                int day = int.Parse(sDay);
                DateTime date = new DateTime(year, month, day);
                if ("get_daily_worktime_sheet".Equals(sAction))
                {
                    Guid jobTitleId = new Guid(sJobTitleId);
                    int pageIndex = int.Parse(sPageIndex);

                    BLJobTitle jobTitleFilter = new BLJobTitle();
                    jobTitleFilter.Id = jobTitleId;

                    AgentDAO agentDao = new AgentDAO();
                    int totalAgents = agentDao.CountAgent(jobTitleFilter, Guid.Empty, string.Empty, Constant.DefaultMinDate, Constant.DefaultMaxDate);
                    int totalPage = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalAgents) / Convert.ToDouble(ContentProvider.PageSize)));

                    if (pageIndex < 1)
                    {
                        pageIndex = 1;
                    }
                    if (pageIndex > totalPage)
                    {
                        pageIndex = totalPage;
                    }

                    DailyWorktimeDAO worktimeDao = new DailyWorktimeDAO();
                    BLDailyWorktimeSheet worktimeTable = worktimeDao.Collect(jobTitleFilter, Guid.Empty, string.Empty,
                        date, totalPage, ContentProvider.PageSize, pageIndex);

                    StringBuilder list = new StringBuilder();
                    list.Append("[");
                    int i = 0;
                    string format = new string('0', Convert.ToString(worktimeTable.AgentWorktimes.Count).Length);
                    foreach (BLDailyWorktime w in worktimeTable.AgentWorktimes)
                    {
                        if (i > 0)
                        {
                            list.Append(",");
                        }
                        list.Append("{\"agentId\":\"");
                        list.Append(w.AgentId);
                        list.Append("\",\"fullName\":\"");
                        list.Append(w.AgentFullName);
                        list.Append("\",\"leaveMorning\":\"");
                        list.Append(w.LeaveMorning);
                        list.Append("\",\"leaveAfternoon\":\"");
                        list.Append(w.LeaveAfternoon);
                        list.Append("\",\"order\":\"");
                        list.Append(((pageIndex-1)*ContentProvider.PageSize+i+1).ToString(format));
                        list.Append("\"}");
                        i++;
                    }
                    list.Append("]");

                    result.Append("{\"status\":true,\"totalPage\":\"");
                    result.Append(totalPage);
                    result.Append("\",\"pageIndex\":\"");
                    result.Append(pageIndex);
                    result.Append("\",\"list\":");
                    result.Append(list);
                    result.Append("}");
                }
                else if ("get_over_worktime_sheet".Equals(sAction))
                {
                    Guid jobTitleId = new Guid(sJobTitleId);
                    int pageIndex = int.Parse(sPageIndex);

                    BLJobTitle jobTitleFilter = new BLJobTitle();
                    jobTitleFilter.Id = jobTitleId;

                    AgentDAO agentDao = new AgentDAO();
                    int totalAgents = agentDao.CountAgent(jobTitleFilter, Guid.Empty, string.Empty, Constant.DefaultMinDate, Constant.DefaultMaxDate);
                    int totalPage = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalAgents) / Convert.ToDouble(ContentProvider.PageSize)));

                    if (pageIndex < 1)
                    {
                        pageIndex = 1;
                    }
                    if (pageIndex > totalPage)
                    {
                        pageIndex = totalPage;
                    }

                    DailyWorktimeDAO worktimeDao = new DailyWorktimeDAO();
                    BLDailyWorktimeSheet worktimeTable = worktimeDao.CollectOverWorktime(jobTitleFilter, Guid.Empty, string.Empty,
                        date, totalPage, ContentProvider.PageSize, pageIndex);

                    StringBuilder list = new StringBuilder();
                    list.Append("[");
                    int i = 0;
                    string format = new string('0', Convert.ToString(worktimeTable.AgentWorktimes.Count).Length);
                    foreach (BLDailyWorktime w in worktimeTable.AgentWorktimes)
                    {
                        if (i > 0)
                        {
                            list.Append(",");
                        }
                        list.Append("{\"agentId\":\"");
                        list.Append(w.AgentId);
                        list.Append("\",\"fullName\":\"");
                        list.Append(w.AgentFullName);
                        string sStartDate = string.Empty;
                        string endDate = string.Empty;
                        string sStartHour = string.Empty;
                        string sStartMin = string.Empty;
                        string sEndHour = string.Empty;
                        string sEndMin = string.Empty;
                        string sTotal = "";
                        string overWorktimeId = "";
                        if (w.OverWorktimes.Count > 0)
                        {
                            overWorktimeId = w.OverWorktimes[0].Id.ToString();
                            sStartDate = w.Date.ToString(Constant.DateFormat);
                            sStartHour = w.OverWorktimes[0].StartTime.Substring(0, 2);
                            sStartMin = w.OverWorktimes[0].StartTime.Substring(3, 2);
                            sEndHour = w.OverWorktimes[0].EndTime.Substring(0, 2);
                            sEndMin = w.OverWorktimes[0].EndTime.Substring(3, 2);
                            sTotal = "00:00";
                            int startHour, startMin, endHour, endMin;
                            double total;
                            if (int.TryParse(sStartHour, out startHour)
                                && int.TryParse(sStartMin, out startMin)
                                && int.TryParse(sEndHour, out endHour)
                                && int.TryParse(sEndMin, out endMin))
                            {
                                if (endHour >= 24)
                                {
                                    endDate = w.Date.AddDays(1).ToString(Constant.DateFormat);
                                    sEndHour = (endHour - 24).ToString("00");
                                }
                                else
                                {
                                    endDate = w.Date.ToString(Constant.DateFormat);
                                }
                                total = (endHour * 60 + endMin) - (startHour * 60 + startMin);
                                sTotal = Math.Floor(total / 60D).ToString("00")+":" + (total % 60).ToString("00");
                            }
                        }
                        list.Append("\",\"overWorktimeId\":\"");
                        list.Append(overWorktimeId);
                        list.Append("\",\"startDate\":\"");
                        list.Append(sStartDate);
                        list.Append("\",\"endDate\":\"");
                        list.Append(endDate);
                        list.Append("\",\"startHour\":\"");
                        list.Append(sStartHour);
                        list.Append("\",\"startMin\":\"");
                        list.Append(sStartMin);
                        list.Append("\",\"endHour\":\"");
                        list.Append(sEndHour);
                        list.Append("\",\"endMin\":\"");
                        list.Append(sEndMin);
                        list.Append("\",\"total\":\"");
                        list.Append(sTotal);
                        list.Append("\",\"order\":\"");
                        list.Append(((pageIndex - 1) * ContentProvider.PageSize + i + 1).ToString(format));
                        list.Append("\"}");
                        i++;
                    }
                    list.Append("]");

                    result.Append("{\"status\":true,\"totalPage\":\"");
                    result.Append(totalPage);
                    result.Append("\",\"pageIndex\":\"");
                    result.Append(pageIndex);
                    result.Append("\",\"list\":");
                    result.Append(list);
                    result.Append("}");
                }
                else if ("get_monthly_worktime_sheet".Equals(sAction))
                {
                    Guid jobTitleId = new Guid(sJobTitleId);
                    int pageIndex = int.Parse(sPageIndex);

                    BLJobTitle jobTitleFilter = new BLJobTitle();
                    jobTitleFilter.Id = jobTitleId;

                    AgentDAO agentDao = new AgentDAO();
                    int totalAgents = agentDao.CountAgent(jobTitleFilter, Guid.Empty, string.Empty, Constant.DefaultMinDate, Constant.DefaultMaxDate);
                    int totalPage = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalAgents) / Convert.ToDouble(ContentProvider.PageSize)));

                    if (pageIndex < 1)
                    {
                        pageIndex = 1;
                    }
                    if (pageIndex > totalPage)
                    {
                        pageIndex = totalPage;
                    }

                    MonthlyWorktimeDAO worktimeDao = new MonthlyWorktimeDAO();
                    BLMonthlyWorktimeSheet worktimeTable = worktimeDao.Collect(jobTitleFilter, Guid.Empty, string.Empty,
                        date, totalPage, ContentProvider.PageSize, pageIndex);

                    StringBuilder list = new StringBuilder();
                    int j = 0;
                    list.Append("[");
                    foreach (BLMonthlyWorktime mw in worktimeTable.AgentsWorktime)
                    {
                        if (j > 0)
                        {
                            list.Append(",");
                        }
                        list.Append("{\"agentId\":\"");
                        list.Append(mw.AgentId);
                        list.Append("\",\"fullName\":\"");
                        list.Append(mw.AgentFullName);
                        list.Append("\",\"days\":[");
                        int i = 0;
                        foreach (BLDailyWorktime w in mw.DaysWorktime)
                        {
                            if (i > 0)
                            {
                                list.Append(",");
                            }
                            list.Append("{\"total\":\"");
                            list.Append(w.Total.ToString("0.0"));
                            list.Append("\",\"leaveMorning\":\"");
                            list.Append(w.LeaveMorning);
                            list.Append("\",\"leaveAfternoon\":\"");
                            list.Append(w.LeaveAfternoon);

                            string morningExp = "";
                            if (w.LeaveMorning == 1)
                            {
                                morningExp = ContentProvider.GetFormat("HasLeaveApplication")
                                    .Replace("{0}", ContentProvider.GetString("Morning"));
                            }
                            else if (w.LeaveMorning == 2)
                            {
                                morningExp = ContentProvider.GetFormat("NoLeaveApplication")
                                    .Replace("{0}", ContentProvider.GetString("Morning"));
                            }
                            string afternoonExp = "";
                            if (w.LeaveAfternoon == 1)
                            {
                                afternoonExp = ContentProvider.GetFormat("HasLeaveApplication")
                                    .Replace("{0}", ContentProvider.GetString("Afternoon"));
                            }
                            else if (w.LeaveAfternoon == 2)
                            {
                                afternoonExp = ContentProvider.GetFormat("NoLeaveApplication")
                                    .Replace("{0}", ContentProvider.GetString("Afternoon"));
                            }

                            list.Append("\",\"morningExp\":\"");
                            list.Append(morningExp);
                            list.Append("\",\"afternoonExp\":\"");
                            list.Append(afternoonExp);

                            list.Append("\"}");
                            i++;
                        }
                        list.Append(",{\"leaveMorning\":\"0\",\"leaveAfternoon\":\"0\",\"bonus\":");
                        float bonus = 0;
                        if (mw.Total >= 28)
                        {
                            bonus = 1;
                            list.Append("true");
                        }
                        else
                        {
                            list.Append("false");
                        }
                        list.Append(",\"total\":\"1.0\",\"bonusExp\":\"");
                        list.Append(ContentProvider.GetString("BonusWorktimeDay"));
                        list.Append("\"}");
                        list.Append("],\"total\":\"");
                        list.Append((mw.Total+bonus).ToString("0.0"));
                        list.Append("\"}");
                        j++;
                    }
                    list.Append("]");

                    result.Append("{\"status\":true,\"totalPage\":\"");
                    result.Append(totalPage);
                    result.Append("\",\"pageIndex\":\"");
                    result.Append(pageIndex);
                    result.Append("\",\"list\":");
                    result.Append(list);
                    result.Append("}");
                }
                else if ("get_monthly_over_worktime_sheet".Equals(sAction))
                {
                    Guid jobTitleId = new Guid(sJobTitleId);
                    int pageIndex = int.Parse(sPageIndex);

                    BLJobTitle jobTitleFilter = new BLJobTitle();
                    jobTitleFilter.Id = jobTitleId;

                    AgentDAO agentDao = new AgentDAO();
                    int totalAgents = agentDao.CountAgent(jobTitleFilter, Guid.Empty, string.Empty, Constant.DefaultMinDate, Constant.DefaultMaxDate);
                    int totalPage = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalAgents) / Convert.ToDouble(ContentProvider.PageSize)));

                    if (pageIndex < 1)
                    {
                        pageIndex = 1;
                    }
                    if (pageIndex > totalPage)
                    {
                        pageIndex = totalPage;
                    }

                    MonthlyWorktimeDAO worktimeDao = new MonthlyWorktimeDAO();
                    BLMonthlyWorktimeSheet worktimeTable = worktimeDao.CollectOverWorktime(jobTitleFilter, Guid.Empty, string.Empty,
                        date, totalPage, ContentProvider.PageSize, pageIndex);

                    StringBuilder list = new StringBuilder();
                    int j = 0;
                    list.Append("[");
                    foreach (BLMonthlyWorktime mw in worktimeTable.AgentsWorktime)
                    {
                        if (j > 0)
                        {
                            list.Append(",");
                        }
                        list.Append("{\"agentId\":\"");
                        list.Append(mw.AgentId);
                        list.Append("\",\"fullName\":\"");
                        list.Append(mw.AgentFullName);
                        list.Append("\",\"days\":[");
                        int i = 0;
                        foreach (BLDailyWorktime w in mw.DaysWorktime)
                        {
                            if (i > 0)
                            {
                                list.Append(",");
                            }
                            list.Append("{\"total\":\"");
                            list.Append(w.TotalOver.ToString("0.0"));
                            string time = string.Empty;
                            if (w.OverWorktimes.Count > 0)
                            {
                                time = ContentProvider.GetFormat("WorkFromTo")
                                    .Replace("{0}", w.OverWorktimes[0].StartTime)
                                    .Replace("{1}", w.OverWorktimes[0].EndTimeStandard);
                            }
                            list.Append("\",\"timeExp\":\"");
                            list.Append(time);
                            list.Append("\"}");
                            i++;
                        }
                        list.Append("],\"total\":\"");
                        list.Append((mw.TotalOver).ToString("0.0"));
                        list.Append("\"}");
                        j++;
                    }
                    list.Append("]");

                    result.Append("{\"status\":true,\"totalPage\":\"");
                    result.Append(totalPage);
                    result.Append("\",\"pageIndex\":\"");
                    result.Append(pageIndex);
                    result.Append("\",\"list\":");
                    result.Append(list);
                    result.Append("}");
                }
                else if ("update_daily_worktime_sheet".Equals(sAction))
                {
                    string sPostData = Request.Params["postData"];
                    string[] rows = sPostData.Split(',');
                    int updateResult = 0;
                    foreach (string row in rows)
                    {
                        string[] es = row.Split('|');
                        Guid agentId = new Guid(es[0]);
                        BLDailyWorktime worktime = new BLDailyWorktime(agentId, date);
                        worktime.LeaveMorning = int.Parse(es[1]);
                        worktime.LeaveAfternoon = int.Parse(es[2]);
                        DailyWorktimeDAO worktimeDao = new DailyWorktimeDAO();
                        updateResult = worktimeDao.Update(worktime, ref errorCode);
                        if (errorCode == 12)
                        {
                            error = ContentProvider.GetMessage("NotAuthorizedDetail")
                                .Replace("{0}",ContentProvider.GetString("DailyWorktime"));
                            status = "false";
                            break;
                        }
                    }
                    result.Append("{\"status\":");
                    result.Append(status);
                    result.Append(",\"error\":\"");
                    result.Append(error);
                    result.Append("\"}");
                }
                else if ("update_over_worktime".Equals(sAction))
                {
                    int updateResult = 0;
                    Guid agentId = new Guid(sAgentId);
                    BLDailyWorktime worktime = new BLDailyWorktime(agentId, date);
                    BLOverWorktime overWorktime = new BLOverWorktime();
                    worktime.OverWorktimes.Add(overWorktime);
                    string sOverWorktimeId = Request.Params["overWorktimeId"];
                    overWorktime.StartTime = Request.Params["startTime"];
                    overWorktime.EndTime = Request.Params["endTime"];
                    DailyWorktimeDAO worktimeDao = new DailyWorktimeDAO();
                    try
                    {
                        overWorktime.Id = new Guid(sOverWorktimeId);
                        updateResult = worktimeDao.UpdateOverWorktime(worktime, ref errorCode);
                    }
                    catch (Exception exp)
                    {
                        Console.Out.WriteLine(exp.Message);
                        overWorktime.Id = Guid.NewGuid();
                        updateResult = worktimeDao.AddOverWorktime(worktime, ref errorCode);
                    }

                    if (errorCode == 12)
                    {
                        status = "false";
                        error = ContentProvider.GetMessage("NotAuthorizedDetail")
                            .Replace("{0}", ContentProvider.GetString("OverWorktime"));
                    }
                    else if (errorCode == 21)
                    {
                        status = "false";
                        error = ContentProvider.GetMessage("ConflictWorktime");
                    }
                    else
                    {
                        status = "true";
                    }

                    result.Append("{\"status\":");
                    result.Append(status);
                    result.Append(",\"overWorktimeId\":\"");
                    result.Append(overWorktime.Id);
                    result.Append("\",\"error\":\"");
                    result.Append(error);
                    result.Append("\"}");
                }
                else if ("remove_over_worktime".Equals(sAction))
                {
                    int updateResult = 0;
                    BLOverWorktime worktime = new BLOverWorktime();
                    string sOverWorktimeId = Request.Params["overWorktimeId"];
                    DailyWorktimeDAO worktimeDao = new DailyWorktimeDAO();
                    worktime.Id = new Guid(sOverWorktimeId);
                    updateResult = worktimeDao.DeleteOverWorktime(worktime, ref errorCode);

                    if (errorCode == 12)
                    {
                        status = "false";
                        error = ContentProvider.GetMessage("NotAuthorizedDetail")
                            .Replace("{0}", ContentProvider.GetString("OverWorktime"));
                    }
                    else if (errorCode == 21)
                    {
                        status = "false";
                        error = ContentProvider.GetMessage("ConflictWorktime");
                    }
                    else
                    {
                        status = "true";
                    }

                    result.Append("{\"status\":");
                    result.Append(status);
                    result.Append(",\"error\":\"");
                    result.Append(error);
                    result.Append("\"}");
                }
            }
            catch (Exception exp)
            {
                Console.Out.WriteLine(exp.Message);
            }

            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(result);
            Response.End();
        }
    }
}
